<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
        <script src="./city.js"></script>
        <title>Document</title>
    </head>
    <body>
        <select id="prov">
            <option>请选择省份</option>
        </select>
        <select id="city">
            <option>请选择城市</option>
        </select>
        <select id="country">
            <option>请选择县区</option>
        </select>
    </body>
    <script>
        $(function () {
            var prov = $("#prov");
            var city = $("#city");
            var country = $("#country");
            var currentProv = 0; //获取当前省份的索引值，用于获取当前省份的城市列表
            var currentCity = 0; //获取当前市的索引值，用用获取当前市的县区
            /*
        加载网页立即执行获取当前省份信息
        */
            (function showProv() {
                for (let i = 0; i < citys.length; i++) {
                    prov.append(
                        "<option " +
                            "value = " +
                            i +
                            ">" +
                            citys[i].name +
                            "</option>"
                    );
                }
            })();
            /*
        当省份改变时触发事件，获取当前省份的市列表
        */
            prov.change(function () {
                currentProv = $("#prov").find("option:selected").val();
                $("#city").html("<option>请选择城市</option>");
                $("#country").html("<option>请选择县区</option>");
                var cityLen = citys[currentProv].city.length;
                for (let i = 0; i < cityLen; i++) {
                    city.append(
                        "<option " +
                            "value = " +
                            i +
                            ">" +
                            citys[currentProv].city[i].name +
                            "</option>"
                    );
                }
            });
            /*
        当市改变城市触发事件，获取当前市的县区列表
        */
            city.change(function () {
                currentCity = $("#city").find("option:selected").val();
                $("#country").html("<option>请选择县区</option>");
                var countryLen =
                    citys[currentProv]["city"][currentCity].area.length;
                for (let i = 0; i < countryLen; i++) {
                    country.append(
                        "<option " +
                            "value = " +
                            i +
                            ">" +
                            citys[currentProv]["city"][currentCity].area[i] +
                            "</option>"
                    );
                }
            });
        });
    </script>
</html>
